<template>
  <div class="container">
    <el-form label-width="100px"
             :model="ruleForm"
             status-icon
             :rules="rules">
      <!-- 讲师头像 -->
      <el-form-item label="头像">
        <!-- 头衔缩略图 -->
        <pan-thumb :image="String(user.portrait)"/>
        <el-button
            type="primary"
            icon="el-icon-upload"
            @click="imagecropperShow=true">上传头像
        </el-button>
      </el-form-item>
      <el-form-item label="姓名">
        <el-col :span="8">
          <el-input v-model="user.name" width="100"/>
        </el-col>
      </el-form-item>
      <el-form-item label="邮箱"
                    prop="email"
                    :rules="[
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
      ]">
        <el-input type="email" v-model="ruleForm.email"/>
      </el-form-item>
      <el-form-item label="账号名">
        <el-col :span="8">
          <el-input v-model="user.account" width="100"/>
        </el-col>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input
            type="password"
            v-model="ruleForm.pass"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input
            type="password"
            v-model="ruleForm.checkPass"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="user.gender">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="职业">
        <el-col :span="16">
          <el-input v-model="user.professional"/>
        </el-col>
      </el-form-item>
      <el-form-item label="电话">
        <el-col :span="8">
          <el-input v-model="user.phoneNum"/>
        </el-col>
      </el-form-item>
      <el-form-item label="出生日期">
        <el-date-picker v-model="user.birthday" type="date">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="兴趣爱好">
        <el-input id="input-textarea" :rows="6" v-model="user.interest" type="textarea" maxlength="50"/>
      </el-form-item>
      <el-form-item label="账号状态">
        <el-select v-model="user.status" placeholder="请选择">
          <el-option label="正常" :value="0"></el-option>
          <el-option label="封禁" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="medium" @click="resetData" id="reset-btn">重置</el-button>
        <el-button type="primary" size="medium" @click="saveUser">保存</el-button>
      </el-form-item>


<!--          <el-form-item>-->
<!--            <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate()">保存</el-button>-->
<!--          </el-form-item>-->
    </el-form>
    <!--上传头像组件-->
    <div id="image-upload">
       <image-upload field="img"
                   @crop-success="cropSuccess"
                   @cropUploadSuccess="cropUploadSuccess"
                   v-model="imagecropperShow"
                   :width="300"
                   :height="300"
                   url="/api/user/uploadPortrait"
                   :headers="headers"
                   :noSquare="true"
                   :key="imagecropperKey"
                   :noRotate="false"
                   img-format="png">
        </image-upload>
    </div>
  </div>
</template>

<script>

// 引入图片上传组件
import ImageUpload from 'vue-image-crop-upload'
import PanThumb from '@/components/PanThumb'
import user from "@/api/admin/admin"
export default {
  // 声明组件
  components: {
    'image-upload': ImageUpload,
    PanThumb,
  },
  data() {
    // 默认头像
    const DefaultPortrait = "https://bluedot-a.oss-cn-hangzhou.aliyuncs.com/bluedot/portrait/2021/09/21/0860dc2efb074bc4bac19c97f7ee342b.png"
    // 表单格式校验
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {

      user: {
        account: null,
        phoneNum: null,
        password: null,
        gender: 0,
        email: null,
        portrait: DefaultPortrait,
        birthday: null,
        name: null,
        status: 0,
        interest: null,
        professional: null,
      },
      // 上传弹窗按钮是否显示, 为true时可以弹出上传图片的页面
      imagecropperShow: false,
      // 上传组件唯一值(key值)
      imagecropperKey: 0,
      // 保存按钮是否禁用
      saveBtnDisabled: false,
      // 图片
      headers: {
        smail: '*_~'
      },
      // the datebase64 url of created image
      cropperImgData: '',
      // 表单格式校验
      ruleForm: {
        pass: '',
        checkPass: '',
        email: '',
      },
      rules: {
        pass: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: validatePass2, trigger: 'blur' }],
      },
    }
  },
  created() {

  },
  methods: {
    getUserDetail(id) {
      user.getUserDetail(id).then(response => {
        this.user = response.data.item
      })
    },
    saveUser() {
      this.user.password = this.ruleForm.checkPass
      this.user.email = this.ruleForm.email
      if (this.user.name == null
        || this.user.portrait == null
        || this.user.password == null
        || this.user.birthday == null
      ) {
        this.$message({
          type: 'error',
          message: '您还有选项未完成，请填完后再保存！'
        })
      }  else {
        user.insertUser(this.user).then(resp => {
          this.user = resp.data.item;
          this.$message({
            type: 'success',
            message: '添加用户成功'
          })
          // 保存后跳转页面
          this.$router.push("/admin/user")
        }).catch(resp => {
          this.$message({
            type: 'error',
            message: resp.message
          })
        })
      }
    },
    resetData() {
      this.ruleForm = {}
      this.user = {}
    },
    // 组件中对close()方法和cropSuccess()方法做了封装
    // 关闭上传图片弹窗
    close() {
      this.imagecropperShow = false
      // 将此值加1是为使图片上传插件每次进行初始化，否则如果上传完成后再次点击更换图片的话会显示已经保存，算是一个bug
      this.imagecropperKey = this.imagecropperKey + 1
    },
    // 裁剪成功后
    cropSuccess(data) {
      this.cropperImgData = data
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
    },
    // 裁剪并且上传成功后
    cropUploadSuccess(jsonData, field) {
      // 上传图片后会返回url地址, 将这个地址的相对路径存入数据库
      console.log("upload ==> " + jsonData.data.item)
      this.user.portrait = jsonData.data.item;
    },

  }
}
</script>

// scoped表示这里定义的样式只在当前页面范围内生效，不会污染到其他的页面
<style scoped>
  .container {
    margin: 20px;
  }
  .el-input {
    width: 300px;
  }
  #input-textarea {
    width: 300px;
  }

  #reset-btn {
    margin-right: 25px;
  }
</style>